package com.flython.aems.management.component;

import com.flython.aems.management.model.CsonParam;
import com.flython.aems.management.model.base.FinalParamPoJo;
import com.flython.aems.management.model.ProfileParam;
import com.flython.aems.management.model.UniqueParam;
import com.flython.aems.management.utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 按照优先级组合参数的参数管理器
 */
@Component
public class PrioritizeParamsManager implements ParamsManager {

    List<AbstractParamsSupplier> paramsSupplierList;

    @Autowired
    public void setParamsSupplierList(List<AbstractParamsSupplier> paramsSupplierList) {
        var cloneList = new LinkedList<AbstractParamsSupplier>();
        cloneList.addAll(paramsSupplierList);
        cloneList.sort(Comparator.comparingInt(sp -> sp.getPriority()));
        this.paramsSupplierList = cloneList;
    }


    @Override
    public List<FinalParamPoJo> getNeFinalParamsForNe(Long neId) {
        Map<String,FinalParamPoJo> finalMap = new HashMap<>();
        paramsSupplierList.forEach(paramsSupplier -> finalMap.putAll(paramsSupplier.selectByNeId(neId)));
        LinkedList<FinalParamPoJo> finalParamPoJos = new LinkedList<>(finalMap.values());
        return finalParamPoJos;
    }


    /**
     * 如果需要实现后改后生效或者其他特异合并需求，只需要对参数修改策略重载就好了，最后决定好需要更新或者删除什么参数，直接确定好策略然后调AbstractParamsSupplier
     * 【当前】默认是所有参数后改后生效，cson不受限制，永远最高
     */
    @Transactional
    public void modifyUniqueParams(Long neId, List<UniqueParam> params){
        //1. 更新数据库
        //TODO: doSomeDBWork();
        //2. 在以等级划分的实现中，需要删除等级比自己低的数据库中的数据
        UniqueParamSupplier uniqueParamSupplier = SpringContextUtil.getBean("uniqueParamSupplier", UniqueParamSupplier.class);
        //2.1 调用数据库，删除低等级的已存在记录
        this.deleteLowLevelParams(neId,params,uniqueParamSupplier.getPriority());
    }

    public void modifyCsonParam(List<CsonParam> params){
        //1. 更新数据库
        //TODO: doSomeDBWork();
        //2. 因为cson等级最高，永远都会覆盖，所以不会做任何事情
    }

    public void modifyProfileParam(List<ProfileParam> params){

    }

    private void deleteLowLevelParams(Long neId, List<UniqueParam> params, int currentPaiority){
        List<AbstractParamsSupplier> readyCallDelete = new LinkedList<>();
        paramsSupplierList.forEach(sp->{
            //跳开cson表的更新
            if (sp.getPriority() > currentPaiority && !(sp instanceof CsonParamSupplier)){
                readyCallDelete.add(sp);
            }
        });
        //2.1 调用数据库，删除低等级的已存在记录
        params.forEach(param->readyCallDelete.forEach(supplier->supplier.deleteSingleParam(neId,param.getName())));
    }


}
